#include "MemDatabase.hpp"

MemDatabase::MemDatabase()
{
	this->last_error = MemDatabaseError::MDB_SUCCESS ;
	
	return;
}

MemDatabase::~MemDatabase()
{
	for( unordered_map<string,MemTable*>::iterator it = tables.begin() ; it != tables.end() ; )
	{
#if MDB_TRACE
		string	table_name = it->second->GetTableName() ;
#endif
		delete it->second;
		tables.erase( it++ );
#if MDB_TRACE
		cout << "TRACE - MemDatabase::~MemDatabase() : delete table[" << table_name << "]" << endl ;
#endif
	}
	
	return;
}

MemDatabaseError MemDatabase::GetLastError()
{
	return last_error;
}

int MemDatabase::GetLastErrorNumber()
{
	return static_cast<int>(last_error);
}

void MemDatabase::SetError( MemDatabaseError error )
{
	last_error = error ;
	return;
}

MemTable *MemDatabase::CreateTable( string table_name , size_t record_size )
{
	MemTable	*table = NULL ;
	
	table = new MemTable( this , table_name , record_size ) ;
	if( table == NULL )
	{
		SetError( MemDatabaseError::MDB_ERROR_ALLOC );
		return NULL;
	}
	
	tables.insert( make_pair(table_name,table) );
	
	return table;
}

bool MemDatabase::DropTable( string table_name )
{
	MemTable	*table = NULL ;
	
	table = QueryTable( table_name ) ;
	if( table == NULL )
	{
		SetError( MemDatabaseError::MDB_ERROR_TABLE_NOT_FOUND );
		return false;
	}
	
	tables.erase( table_name );
	delete table;
	
	return true;
}

bool MemDatabase::DropTable( MemTable *table )
{
	return DropTable( table->GetTableName() );
}

MemTable *MemDatabase::QueryTable( string table_name )
{
	return tables.at( table_name );
}

